package com.longrise.android.byjk.plugins.aboutme.personalInfo.caculate;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;

import java.io.ByteArrayOutputStream;

/**
 * Created by sujizhong on 2016/12/20.
 */

public class BitmapCaculate {

    public static Bitmap decodeBitmapFromLocalPath(String path, int width, int height) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);
        options.inSampleSize = caculateInSampleSize(options, width, height);
        options.inJustDecodeBounds = false;
        Bitmap bitmap = BitmapFactory.decodeFile(path, options);
        return bitmap;
    }

    private static int caculateInSampleSize(BitmapFactory.Options op, int reqWidth, int reqHeight) {
        int width = op.outWidth;
        int height = op.outHeight;
        int inSampleSize = 1;
        if (width > reqWidth || height > reqHeight) {
            int widthRadio = Math.round((float) width / (float) reqWidth);
            int heightRadio = Math.round((float) height / (float) reqHeight);
            inSampleSize = Math.max(widthRadio, heightRadio);
        }
        return inSampleSize;
    }

    public static String bitmapToBase64(Bitmap bitmap) {
        String result = "";
        if (bitmap != null) {
            ByteArrayOutputStream baos = null;
            try {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 90, baos);
                result = Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT);
            } catch (Exception e) {
                e.printStackTrace();

            } finally {
                if (baos != null) {
                    try {
                        baos.flush();
                        baos.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return result;
    }
}
